package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSONObject;
import com.ytjj.qmyx.supplychain.common.configuration.LINKPlatformConfig;
import com.ytjj.qmyx.supplychain.common.configuration.LinkConfigObject;
import com.ytjj.qmyx.supplychain.common.enums.AbroadOrderPushTypeEnum;
import com.ytjj.qmyx.supplychain.common.enums.LinkPlatformMethodEnum;
import com.ytjj.qmyx.supplychain.common.model.request.UpdateOrderInfoRequest;
import com.ytjj.qmyx.supplychain.common.model.request.link.OrderUpdateUploadLinkRequest;
import com.ytjj.qmyx.supplychain.mapper.AbroadOrderRecordMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerOrderMapper;
import com.ytjj.qmyx.supplychain.mapper.CebOrderMapper;
import com.ytjj.qmyx.supplychain.mapper.OrdersMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.CebOrder;
import com.ytjj.qmyx.supplychain.mapper.entity.YxAbroadOrderRecord;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerOrder;
import com.ytjj.qmyx.supplychain.mapper.entity.YxOrders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 跨境订单处理类
 */
@Slf4j
@Service
public class AbroadService {
    @Resource
    private AbroadOrderRecordMapper abroadOrderRecordMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Resource
    private CebOrderMapper cebOrderMapper;
    @Resource
    private LINKPlatformConfig linkPlatformConfig;
    @Autowired
    private OrderService orderService;

    /**
     * 处理上传abroad-订单修改
     * @param request
     */
    public boolean updateAbroadOrder(UpdateOrderInfoRequest request) {
        //1.查询发送记录
        String childOrderNo = request.getChildOrderNo();
        Example example = new Example(YxAbroadOrderRecord.class);
        example.createCriteria()
                .andEqualTo("orderNo", childOrderNo)
        .andEqualTo("type", AbroadOrderPushTypeEnum.ADD.getCode());
        example.orderBy("id").desc();
        List<YxAbroadOrderRecord> yxAbroadOrderRecords = abroadOrderRecordMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(yxAbroadOrderRecords)) {
            return true;
        }
        //2.查询下面操作需要用到的信息
        Example bankerOrderExample = new Example(YxBankerOrder.class);
        bankerOrderExample.createCriteria().andEqualTo("childOrderNo", childOrderNo);
        YxBankerOrder bankerOrder = bankerOrderMapper.selectOneByExample(bankerOrderExample);
        if (null == bankerOrder) {
            log.error("===供应商订单表找不到订单信息==={}", childOrderNo);
            return true;
        }

        Example ordersExample = new Example(YxOrders.class);
        ordersExample.createCriteria().andEqualTo("childOrderNo", childOrderNo);
        YxOrders orders = ordersMapper.selectOneByExample(ordersExample);
        if (null == orders) {
            log.error("===供应商订单在供应链订单表查询不到==={}", childOrderNo);
            return true;
        }
        //获取供应商的link平台参数
        List<LinkConfigObject> matchList = linkPlatformConfig.getLinks().stream().filter(link -> link.getBankerId().equals(orders.getBankerId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(matchList)) {
            log.error("===数据匹配异常==={}", orders.getBankerId());
            return true;
        }
        LinkConfigObject linkConfigObject = matchList.get(0);
        String externalShopName = linkConfigObject.getExternalShopName();
        String ownerUserId = linkConfigObject.getOwnerUserId();
        String code = linkConfigObject.getCode();
        String secretKey = linkConfigObject.getSecretKey();

        YxAbroadOrderRecord orderRecord = yxAbroadOrderRecords.get(0);
        if ("WMS".equals(orderRecord.getServiceName())) {
            // do some thing
        }
        if ("LINK".equals(orderRecord.getServiceName())) {
            return handleToLinkByOrderUpdate(bankerOrder, orders, code, secretKey);
        }
        return true;
    }


    /**
     * 处理上传LINK-订单修改
     * 这里能修改的信息非常有限，仅限于：
     * 身份证信息 & 支付单号
     * @param bankerOrder
     * @return
     */
    private boolean handleToLinkByOrderUpdate(YxBankerOrder bankerOrder, YxOrders orders, String code, String secretKey) {
        Example cebOrderExample = new Example(CebOrder.class);
        cebOrderExample.createCriteria().andEqualTo("orderNo", bankerOrder.getChildOrderNo());
        CebOrder cebOrder = cebOrderMapper.selectOneByExample(cebOrderExample);
        if (null == cebOrder) {
            log.error("===报送海关电子订单表查询不到数据==={}", bankerOrder.getChildOrderNo());
            return false;
        }
        String payType = "01";
        if ("财付通支付科技有限公司".equals(cebOrder.getPayName())) {
            payType = "02";
        }
        OrderUpdateUploadLinkRequest request = OrderUpdateUploadLinkRequest.builder()
                .externalOrderCode(bankerOrder.getChildOrderNo())
                .buyerName(bankerOrder.getUserName())
                .buyerIDNo(orders.getAuthenticatedCard())
                .payType(payType)
                .payOrderId(cebOrder.getPayTransactionId())
                .build();

        String resp = orderService.LINK_Request(JSONObject.toJSONString(request),
                LinkPlatformMethodEnum.ADD.getCode(),
                code,
                secretKey);

        Map<String, Object> resultMap = JSONObject.parseObject(resp, Map.class);
        log.info("===link平台修改订单上传返回接口：{}", resultMap);
        if (!(boolean)resultMap.get("success")) {
            return false;
        }
        return true;
    }
}
